package one.four.eleven;

import java.util.Arrays;

public class StaticSETofInts {
    private int[] a;

    public StaticSETofInts(int[] keys) {

        // defensive copy
        a = new int[keys.length];
        for (int i = 0; i < keys.length; i++)
            a[i] = keys[i];

        // sort the integers
        Arrays.sort(a);

        // check for duplicates
        /*
        for (int i = 1; i < a.length; i++)
            if (a[i] == a[i-1])
                throw new IllegalArgumentException("Argument arrays contains duplicate keys.");
       */         
    }
    public boolean contains(int key) {
        return rank(key) != -1;
    }
    public int rank(int key) {
        int lo = 0;
        int hi = a.length - 1;
        while (lo <= hi) {
            // Key is in a[lo..hi] or not present.
            int mid = lo + (hi - lo) / 2;
            if      (key < a[mid]) hi = mid - 1;
            else if (key > a[mid]) lo = mid + 1;
            else return mid;
        }
        return -1;
    }
    
    public int howMany(int key) {
    	int idx=rank(key);
    	
    	if(idx!=-1) {
    		int c=1;
    		int b=idx+1;
    		while(b<a.length && a[b]==key) {
    			c++;
    			b++;
    		}
    		b=idx-1;
    		while(b>=0 && a[b]==key) {
    			c++;
    			b--;
    		}
    		return c;
    	}
    	return 0;
    }
    
    public static void main(String[] args) {
		int[] a= {2,1,3,5,1,4};
		StaticSETofInts s=new StaticSETofInts(a);
		int c=s.howMany(1);
		System.out.println(c);
;	}
    
}
